package sif.Activity;

import sif.Activity.R;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sif.FacebookSDK.AsyncFacebookRunner;
import sif.FacebookSDK.DialogError;
import sif.FacebookSDK.Facebook.DialogListener;
import sif.FacebookSDK.Facebook;
import sif.FacebookSDK.FacebookError;
import sif.FacebookSDK.AsyncFacebookRunner.RequestListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import sif.PullToRefreshListView.*;

public class MainActivity extends Activity implements OnClickListener {

	private PullToRefreshListView pullToRefreshListView;

	// Your Facebook APP ID
	private static String APP_ID = "275646375845574";// "308180782571605"; //
														// Replace with your App
														// ID

	// Instance of Facebook Class
	private Facebook facebook = new Facebook(APP_ID);
	private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	private SharedPreferences mPrefs;

	// Buttons
	Button btnFbLogin;
	Button btnFbGetProfile;
	Button btnPostToWall;
	Button btnShowAccessTokens;
	Button btnTestGraphApi;

	LinearLayout topFrame;
	LinearLayout contentFrame;
	LinearLayout botFrame;

	LayoutInflater inflater;

	List<Friend> friendObjects;
	ListView friendsList;

	int friends_count = 0;
	ProgressDialog pd;

	// @Override
	// public void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// super.onActivityResult(requestCode, resultCode, data);
	//
	// facebook.authorizeCallback(requestCode, resultCode, data);
	// }

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(sif.Activity.R.layout.master);

		
		
		pd = new ProgressDialog(this);

		mAsyncRunner = new AsyncFacebookRunner(facebook);

		 loginToFacebook();

		topFrame = (LinearLayout) findViewById(R.id.layoutTopMenu);
		contentFrame = (LinearLayout) findViewById(R.id.layoutContent);
		botFrame = (LinearLayout) findViewById(R.id.layoutBottomMenu);

		inflater = getLayoutInflater();
		View topMenu = inflater.inflate(R.layout.top_menu, null);
		View botMenu = inflater.inflate(R.layout.bot_menu, null);

		topFrame.addView(topMenu);
		botFrame.addView(botMenu);

		Display display = getWindowManager().getDefaultDisplay();
		int screenWidth = display.getWidth();
		int screenHeight = display.getHeight();

		// 40*2 top + menu height and 50 is app title height
		int contentHeight = screenHeight - (100 + 100 + 100);

		Log.i("width", "" + screenWidth);
		Log.i("height", "" + screenHeight);
		Log.i("contentHeight", "" + contentHeight);

		topFrame.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, 100));
		contentFrame.setLayoutParams(new LinearLayout.LayoutParams(screenWidth,
				contentHeight));
		botFrame.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, 150));

		Log.i("Theight", "" + topFrame.getHeight());
		Log.i("Cheight", "" + contentFrame.getHeight());
		Log.i("Bheight", "" + botFrame.getHeight());

		((Button) findViewById(R.id.btHome)).setOnClickListener(this);
		((Button) findViewById(R.id.btFriends)).setOnClickListener(this);
		((Button) findViewById(R.id.btProfile)).setOnClickListener(this);
		((Button) findViewById(R.id.btNewFeeds)).setOnClickListener(this);
		((Button) findViewById(R.id.btAlbum)).setOnClickListener(this);
		
		
	}

	class MyArrayAdapter extends ArrayAdapter<Friend> {

		public MyArrayAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
			// TODO Auto-generated constructor stub
		}

		public MyArrayAdapter(Context context, int textViewResourceId,
				List<Friend> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v = convertView;
			if (v == null) {
				LayoutInflater inflater = getLayoutInflater();
				v = inflater.inflate(R.layout.row_friends_list, null);
			}
			TextView tvName = (TextView) v.findViewById(R.id.tvFriendName);
			tvName.setText(this.getItem(position).name);
			ImageView ivAvatar = (ImageView) v
					.findViewById(R.id.ivFriendAvatar);
			URL img_url = null;
			Bitmap avatar = null;
			try {
				img_url = new URL("https://graph.facebook.com/"
						+ this.getItem(position).id + "/picture");
				try {
					avatar = BitmapFactory.decodeStream(img_url
							.openConnection().getInputStream());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ivAvatar.setImageBitmap(avatar);
				// friends_count--;
//				friends_count++;
//				Log.i("friends_count", "" + friends_count);
//				// if(friends_count <= 15 || friends_count <= 0 ){
//				if (friends_count >= 5) {
//					handler.sendEmptyMessage(FINISH_LOAD_FRIEND_LIST);
//				}
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
//				handler.sendEmptyMessage(FINISH_LOAD_FRIEND_LIST);
			}

			return v;
		}

	}

	class Friend {
		public String id, name;

		public Friend(String id, String name) {
			this.id = id;
			this.name = name;
		}
	}

	/**
	 * Function to login into facebook
	 * */
	public void loginToFacebook() {

		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			facebook.setAccessToken(access_token);

			// btnFbLogin.setVisibility(View.INVISIBLE);
			//
			// // Making get profile button visible
			// btnFbGetProfile.setVisibility(View.VISIBLE);
			//
			// // Making post to wall visible
			// btnPostToWall.setVisibility(View.VISIBLE);
			//
			// // Making show access tokens button visible
			// btnShowAccessTokens.setVisibility(View.VISIBLE);
			//
			// btnTestGraphApi.setVisibility(View.VISIBLE);

			Log.d("FB Sessions", "" + facebook.isSessionValid());
		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this, new String[] { "email", "publish_stream",
					"read_stream" }, new DialogListener() {

				@Override
				public void onCancel() {
					// Function to handle cancel event
				}

				@Override
				public void onComplete(Bundle values) {
					// Function to handle complete event
					// Edit Preferences and update facebook acess_token
					SharedPreferences.Editor editor = mPrefs.edit();
					editor.putString("access_token", facebook.getAccessToken());
					editor.putLong("access_expires",
							facebook.getAccessExpires());
					editor.commit();

					Toast.makeText(MainActivity.this, "Login successfully",
							Toast.LENGTH_LONG).show();
					Log.i("thaile", "Login success \n access token : " + facebook.getAccessToken());
					
					// // Making Login button invisible
					// btnFbLogin.setVisibility(View.INVISIBLE);
					//
					// // Making logout Button visible
					// btnFbGetProfile.setVisibility(View.VISIBLE);
					//
					// // Making post to wall visible
					// btnPostToWall.setVisibility(View.VISIBLE);
					//
					// // Making show access tokens button visible
					// btnShowAccessTokens.setVisibility(View.VISIBLE);
					//
					// btnTestGraphApi.setVisibility(View.VISIBLE);
				}

				@Override
				public void onError(DialogError error) {
					// Function to handle error
					Toast.makeText(MainActivity.this, "Login failed",
							Toast.LENGTH_LONG).show();
				}

				@Override
				public void onFacebookError(FacebookError fberror) {
					// Function to handle Facebook errors
					Toast.makeText(MainActivity.this, "Login failed",
							Toast.LENGTH_LONG).show();
				}

			});
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
	}

	/**
	 * Get Profile information by making request to Facebook Graph API
	 * */
	public void getProfileInformation() {
		mAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject profile = new JSONObject(json);

					// getting name of the user
					final String name = profile.getString("name");

					// getting email of the user
					final String email = profile.getString("email");

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getApplicationContext(),
									"Name: " + name + "\nEmail: " + email,
									Toast.LENGTH_LONG).show();
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	/**
	 * Function to post to facebook wall
	 * */
	public void postToWall() {
		// post on user's wall.
		facebook.dialog(this, "feed", new DialogListener() {

			@Override
			public void onFacebookError(FacebookError e) {
			}

			@Override
			public void onError(DialogError e) {
			}

			@Override
			public void onComplete(Bundle values) {
			}

			@Override
			public void onCancel() {
			}
		});

	}

	/**
	 * Function to show Access Tokens
	 * */
	public void showAccessTokens() {
		String access_token = facebook.getAccessToken();

		Toast.makeText(getApplicationContext(),
				"Access Token: " + access_token, Toast.LENGTH_LONG).show();
	}

	/**
	 * Function to Logout user from Facebook
	 * */
	public void logoutFromFacebook() {
		mAsyncRunner.logout(this, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Logout from Facebook", response);
				if (Boolean.parseBoolean(response) == true) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// make Login button visible
							btnFbLogin.setVisibility(View.VISIBLE);

							// making all remaining buttons invisible
							btnFbGetProfile.setVisibility(View.INVISIBLE);
							btnPostToWall.setVisibility(View.INVISIBLE);
							btnShowAccessTokens.setVisibility(View.INVISIBLE);
						}

					});

				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	/**
	 * get the posts made by the "platform" page
	 * */
	public void getPostsByPlatformPage() {
		mAsyncRunner.request("platform/posts", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject profile = new JSONObject(json);

					final String return_json = profile.toString();
					Log.i("return json", return_json);

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getApplicationContext(),
									"json: " + return_json, Toast.LENGTH_LONG)
									.show();
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	/**
	 * get new feeds
	 * */
	public void getNewFeeds() {
		// facebook.authorize(this, new String[] {"read_stream"},
		// new DialogListener() {
		//
		// @Override
		// public void onFacebookError(FacebookError e) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onError(DialogError e) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onComplete(Bundle values) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onCancel() {
		// // TODO Auto-generated method stub
		//
		// }
		// });

		mAsyncRunner.request("me/home", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("new feed", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject profile = new JSONObject(json);

					final String return_json = profile.toString();
					Log.i("return json", return_json);

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getApplicationContext(),
									"json: " + return_json, Toast.LENGTH_LONG)
									.show();
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	/**
	 * get your friends list
	 * */
	public void getFriends() {
		mAsyncRunner.request("me/friends", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Friends", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject json_response = new JSONObject(json);

					final String return_json = json_response.toString();
					Log.i("return json", return_json);

					JSONArray arr = json_response.getJSONArray("data");
					for (int i = 0; i < arr.length(); i++) {
						JSONObject obj = arr.getJSONObject(i);
						Log.i("name", obj.getString("name"));
						friendObjects.add(new Friend(obj.getString("id"), obj
								.getString("name")));
					}

					// friends_count = arr.length();
					// Log.i("friends_count", ""+ friends_count);

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							handler.sendEmptyMessage(LOADING_FRIEND_LIST);
							// Toast.makeText(getApplicationContext(), "Name: "
							// + name + "\nEmail: " + email,
							// Toast.LENGTH_LONG).show();
							Toast.makeText(getApplicationContext(),
									"json: " + return_json, Toast.LENGTH_LONG)
									.show();

						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	/**
	 * get your friends list
	 * */
	public void getFriendsPaging() {
		// String access_token = mPrefs.getString("access_token", null);
		//
		// if (access_token != null) {
		// facebook.setAccessToken("AAAAAAITEghMBAEJe6zZB2ARt5BwzrcMkZC18OpZCCZB9z3IooiV8AmzLmiuHz6hdGS62gmaQZCdqZAQEAokTSueZBD4W98UtUJ6WgbKp4A7iLeKLOujAc2a");
		// facebook.setAccessToken(access_token);

		Bundle params = new Bundle();
		// params.putBoolean("redirect", true);
		// params.putInt("value", 1);
		params.putString("limit", "10");
		params.putString("offset", "0");

		mAsyncRunner.request("me/friends", params, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Friends", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject json_response = new JSONObject(json);

					final String return_json = json_response.toString();
					Log.i("return json", return_json);

					JSONArray arr = json_response.getJSONArray("data");
					for (int i = 0; i < arr.length(); i++) {
						JSONObject obj = arr.getJSONObject(i);
						Log.i("name", obj.getString("name"));
						friendObjects.add(new Friend(obj.getString("id"), obj
								.getString("name")));
					}

					// friends_count = arr.length();
					// Log.i("friends_count", ""+ friends_count);

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							handler.sendEmptyMessage(LOADING_FRIEND_LIST);
							// Toast.makeText(getApplicationContext(), "Name: "
							// + name + "\nEmail: " + email,
							// Toast.LENGTH_LONG).show();
							Toast.makeText(getApplicationContext(),
									"json: " + return_json, Toast.LENGTH_LONG)
									.show();

						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
		// }

	}

	public final int LOADING_FRIEND_LIST = 1;
	public final int FINISH_LOAD_FRIEND_LIST = 2;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
//			Bundle receiveBundle = msg.getData();
			// if(msg.what == FINISH_LOADING_SAVED_STATE){
			// AssignmentActivity.this.pd.dismiss();
			// }
			// else{
			// int i = receiveBundle.getInt("percent");
			// pd.setTitle("Please wait");
			// pd.setMessage("Loading..." + i + "%");
			// }
			if (msg.what == LOADING_FRIEND_LIST) {
				Log.i("load list friends", "Prepare");

				if (friendObjects.size() > 0) {
					Log.i("load list friends", "OK");
					MyArrayAdapter myArrayAdaper = new MyArrayAdapter(
							MainActivity.this, R.layout.row_friends_list,
							friendObjects);
//					friendsList.setAdapter(myArrayAdaper);
					pullToRefreshListView.setAdapter(myArrayAdaper);
				}
			} else if (msg.what == FINISH_LOAD_FRIEND_LIST) {
				pd.dismiss();
			}

		}

	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btFriends:
			pd.setTitle("Loading friends list");
			pd.setMessage("Please waiting, loading...");
			pd.show();

			friendObjects = new ArrayList<Friend>();
			View list = inflater.inflate(R.layout.friends_list, null);
			contentFrame.addView(list);
//			friendsList = (ListView) findViewById(R.id.FriendsList);

			getFriends();
			break;
		case R.id.btProfile:
//			pd.setTitle("Loading friends list");
//			pd.setMessage("Please waiting, loading...");
//			pd.show();

			friendObjects = new ArrayList<Friend>();
			View list1 = inflater.inflate(R.layout.friends_list, null);
			contentFrame.addView(list1);
//			friendsList = (ListView) findViewById(R.id.FriendsList);
//			pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);
			
			pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);				
			
			pullToRefreshListView.setOnRefreshListener(new sif.PullToRefreshListView.PullToRefreshListView.OnRefreshListener() {
				
				@Override
				public void onRefresh() {
					// Your code to refresh the list contents goes here

					// Make sure you call listView.onRefreshComplete()
					// when the loading is done. This can be done from here or any
					// other place, like on a broadcast receive from your loading
					// service or the onPostExecute of your AsyncTask.

					// For the sake of this sample, the code will pause here to
					// force a delay when invoking the refresh
					pullToRefreshListView.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							pullToRefreshListView.onRefreshComplete();
						}
					}, 2000);
				}
			});
			
			getFriendsPaging();

			// getProfileInformation();
			break;
		case R.id.btHome:
			// postToWall();
			loginToFacebook();
			break;
		case R.id.btAlbum:
			showAccessTokens();
			break;
		case R.id.btn_test_api:
			getPostsByPlatformPage();
			// getNewFeeds();
			break;
		default:
			break;
		}

	}

}
